import json
import os
from pathlib import Path

from c_symbol_table import construct_symbol_table
from code_kind import CodeKind

def rebuilt_header_information(filename, header_definitions, symbol_table, output_directory, include_dirs):
    if not os.path.exists(output_directory):
        return header_definitions, symbol_table

    json_path = Path(output_directory) / (filename + "_output.json")
    if not os.path.exists(json_path):
        return header_definitions, symbol_table

    with open(json_path, "r") as f:
        data = json.load(f)

    if data and "C" in data and "code" in data["C"]:
        code_blocks = data["C"]["code"]
        code_list = []
        for idx, code_block in code_blocks.items():
            kind = code_block["kind"]
            code = code_block["code"]
            #if kind == CodeKind.COMMENT or \
            if kind == CodeKind.INCLUDE or \
                kind == CodeKind.MACRO or \
                kind == CodeKind.STRUCT or \
                kind == CodeKind.ENUM or \
                kind == CodeKind.UNION or \
                kind == CodeKind.TYPEDEF or \
                kind == CodeKind.GLOBAL_VAR:
                #if code not in header_definitions:
                #    header_definitions.append(code)
                pass
            else:
                code_list.append(code_block)
         
        code_idx = 0
        data["C"]["code"] = dict()
        for code_block in code_list:
            data["C"]["code"][str(code_idx)] = code_block
            code_idx += 1

        tmp_header_file = "tmp_gen_header.h"
        definitions = []
        for item in header_definitions:
            if not isinstance(item, list):
                continue
            if len(item) != 2:
                continue
            definitions.append(item[0])
        with open(tmp_header_file, "w") as hfile:
            hfile.write("\n".join(definitions))
            #hfile.write(header_definitions)

        symbol_table = construct_symbol_table(tmp_header_file, include_dirs)

        data["C"]["header_definitions"] = header_definitions
        data["C"]["symbol_table"] = symbol_table

        with open(json_path, "w") as jfile:
            json.dump(data, jfile, indent=4)

        return header_definitions, symbol_table


    else:
        return header_definitions, symbol_table
